package ua.org.nuos.sdms.clientgui.client.handlers;

import ua.org.nuos.sdms.clientgui.client.context.Messages;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.AttachUserToGroupEvent;
import ua.org.nuos.sdms.clientgui.client.events.ChangeCurrentGroupEvent;
import ua.org.nuos.sdms.clientgui.client.events.ErrorMessageEvent;
import ua.org.nuos.sdms.clientgui.client.events.InfoMessageEvent;
import ua.org.nuos.sdms.clientgui.client.listeners.AttachUserToGroupListener;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.middle.entity.Group;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 08.03.12
 * Time: 17:46
 * To change this template use File | Settings | File Templates.
 */
public class AttachUserToGroupHandler implements AttachUserToGroupListener {
    @Override
    public void attach(AttachUserToGroupEvent event) {
        try {
            Group group = event.getGroup();
            boolean isUserInGroup = AppProxy.getInstance().getServiceLocator().getClientBean().isCurrentUserInGroup(group.getId());
            if (isUserInGroup) {
                AppProxy.getInstance().getController(GlobalBoard.ID).fire(
                        new InfoMessageEvent(String.format(Messages.USER_IS_ALREADY_IN_GROUP_MESSAGE, group.getName())));
            } else {
                AppProxy.getInstance().getServiceLocator().getClientBean()
                        .attachCurrentUserToGroup(group.getId(), UserInGroup.Type.USER);
            }
            AppProxy.getInstance().getController(GlobalBoard.ID).fire(new ChangeCurrentGroupEvent(group));
        } catch (Exception e) {
            Logger.getAnonymousLogger().log(Level.WARNING, "Cant attach user to group", e);
            AppProxy.getInstance().getController(GlobalBoard.ID).fire(new ErrorMessageEvent(Messages.ACTION_ERROR));
        }
    }
}
